#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <arpa/inet.h>
#include <assert.h>
#include <sys/socket.h>

#define MAXSIZE 512

int main(int argc, char **argv) {
    if (argc != 3) {
        printf("usage %s <mulicast_ip> <mulitcast_port>\n", argv[0]);
        return 0;
    }
    struct sockaddr_in addr;
    struct ip_mreq join_addr;
    int sockfd = socket(PF_INET, SOCK_DGRAM, 0);
    assert(sockfd != -1);

    memset(&addr, 0, sizeof(addr));
    addr.sin_family = AF_INET;
    // 多播源地址为INADDR_ANY
    addr.sin_addr.s_addr = htonl(INADDR_ANY); 
    addr.sin_port = htons(atoi(argv[2]));

    int rc = bind(sockfd, (struct sockaddr *)&addr, sizeof(addr));
    assert(rc != -1);
    // 设置多播地址
    join_addr.imr_multiaddr.s_addr = inet_addr(argv[1]);
    join_addr.imr_interface.s_addr = htonl(INADDR_ANY); 
   
    setsockopt(sockfd, IPPROTO_IP, IP_ADD_MEMBERSHIP, (void *)&join_addr, sizeof(join_addr));

    char recvbuff[MAXSIZE] = {0};
    struct sockaddr sender_addr;
    socklen_t len = sizeof(sender_addr);

    while (1) {
        int strlen = recvfrom(sockfd, recvbuff, MAXSIZE, 0, NULL, 0);
        printf("strlen = %d\n", strlen);
        if (strlen == 0)
            break;
        recvbuff[strlen] = 0;
        printf("%s\n", recvbuff);
    }
    close(sockfd);
    return 0;
}